import requests
import os




def downloadfiles(forecotime,filehours,datype,extentgeo,outpath):

    url=f"https://nomads.ncep.noaa.gov/cgi-bin/filter_gfs_0p25.pl?dir=/gfs.{forecotime[:8]}/{forecotime[8:]}/atmos&file=gfs.t{forecotime[8:]}z.pgrb2.0p25.f{filehours}&{datype}=on&all_lev=on&subregion=&toplat={extentgeo[3]}&leftlon={extentgeo[0]}&rightlon={extentgeo[2]}&bottomlat={extentgeo[1]}"    
    re=requests.get(url=url)
    print(re.status_code)
    savepath=os.path.join(outpath,f"gfs.t{forecotime[8:]}z.pgrb2.0p25.f{filehours}")
    with open(savepath,"wb")as w:
        w.write(re.content)
    print(f"gfs.t{forecotime[8:]}z.pgrb2.0p25.f{filehours}")



def downloadselect(foretime:str,starthour:int,endhour:int,extengeo:list,outpath_prate:str, outpath_csnow:str):
    """_summary_

    Args:
        forecdate (str): 预报起始时间
        starthours (int): 开始小时数
        endhours (int): 结束小时数
        extengeo (list): 下载数据范围
        outpath_prate (str): 下载降水量数据存放文件夹
        outpath_csnow (str): 下载雪分类数据存放位置
    """
       
    i=starthour
    while i <=endhour:
        filehours=str(i).rjust(3,"0")
        downloadfiles(foretime,filehours,"var_PRATE",extengeo,outpath_prate)#var_CSNOW,var_PRATE      
        downloadfiles(foretime,filehours,"var_CSNOW",extengeo,outpath_csnow)#var_CSNOW,var_PRATE

        if i>=120:
            i+=3
        else:
            i+=1

